import cv2 as cv
import numpy as np
import os

filename = r'pic.png'
filename2 = r'pic2.png'
filename6 = r'pic6.png'

def otsu(imgfilename):

    img = cv.imread(imgfilename)
    #cv.imshow('original img',img)
    gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)

    otsuthreshold,otsuimg = cv.threshold(gray,0,255,cv.THRESH_OTSU)

    #shape(高度，宽度，通道数)
    rows = otsuimg.shape[1]
    cols = otsuimg.shape[0]

    allshowimg = np.zeros((cols,rows*2,3),np.uint8)

    allshowimg[0:cols,0:rows, :] = img[0:cols, 0:rows, :]
    allshowimg[0:cols,rows:rows*2, 0] = otsuimg[0:cols, 0:rows]
    allshowimg[0:cols,rows:rows*2, 1] = otsuimg[0:cols, 0:rows]
    allshowimg[0:cols,rows:rows*2, 2] = otsuimg[0:cols, 0:rows]

    cv.imshow("otsuimg",allshowimg)
    print(otsuthreshold)

    (newfilename, extension) = os.path.splitext(imgfilename)
    cv.imwrite(newfilename+'_otsuimg.jpg',allshowimg)
    cv.waitKey()

otsu(filename)
otsu(filename2)
otsu(filename6)

cv.destroyAllWindows()
